package com.jiutong.meipengdai.views.dialog;

import android.annotation.SuppressLint;
import android.content.res.AssetManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseApplicationLike;
import com.jiutong.meipengdai.views.wheelview.OnWheelChangedListener;
import com.jiutong.meipengdai.views.wheelview.WheelView;
import com.jiutong.meipengdai.views.wheelview.adapter.ArrayWheelAdapter;
import com.jiutong.meipengdai.views.wheelview.model.CityModel;
import com.jiutong.meipengdai.views.wheelview.model.DistrictModel;
import com.jiutong.meipengdai.views.wheelview.model.ProvinceModel;
import com.jiutong.meipengdai.views.wheelview.model.XmlParserHandler;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by suxi on 2017/6/8.
 */

@SuppressLint("ValidFragment")
public class CitySelectedDialog extends DialogFragment implements OnWheelChangedListener, View.OnClickListener{

    private View mContainer;
    private WheelView wv_province;
    private WheelView wv_city;
    private WheelView wv_district;
    private Button btn_ok;
    private Button btn_cancel;

    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName = "";
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName = "";
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode = "";

    //默认选中的省的位置
    private int provinceIndex = 0;
    private int cityIndex = 0;
    private int areaIndex = 0;
    private OnDialogClickListener mListener;

    /**
     * 解析省市区的XML数据
     */

    protected void initProvinceDatas() {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = getContext().getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            // */ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {

                if(TextUtils.isEmpty(mCurrentProviceName))
                    mCurrentProviceName = provinceList.get(0).getName();


                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0)
                            .getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            // */
            mProvinceDatas = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                if(mProvinceDatas[i].contains(mCurrentProviceName)){
                    provinceIndex = i;
                }
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j)
                            .getDistrictList();
                    String[] distrinctNameArray = new String[districtList
                            .size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList
                            .size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(
                                districtList.get(k).getName(), districtList
                                .get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(),
                                districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //去掉dialog的标题，需要在setContentView()之前
        this.getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = this.getDialog().getWindow();
        //去掉dialog默认的padding
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的位置在底部
        lp.gravity = Gravity.BOTTOM;
        //设置dialog的动画
        lp.windowAnimations = R.style.dialog_animation;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
        mContainer = inflater.inflate(R.layout.dialog_city_select, null);

        initView();
        initEvent();
        setUpData();

        setCancelable(false);
        return mContainer;
    }

    private void initView() {
        wv_province = (WheelView) mContainer.findViewById(R.id.id_province);
        wv_city = (WheelView) mContainer.findViewById(R.id.id_city);
        wv_district = (WheelView) mContainer.findViewById(R.id.id_district);
        btn_ok = (Button) mContainer.findViewById(R.id.btn_ok);
        btn_cancel =  (Button) mContainer.findViewById(R.id.btn_cancel);
    }

    private void initEvent() {
        // 添加change事件
        wv_province.addChangingListener(this);
        // 添加change事件
        wv_city.addChangingListener(this);
        // 添加change事件
        wv_district.addChangingListener(this);

        // 添加onclick事件
        btn_ok.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
    }

    private void setUpData() {
        initProvinceDatas();
        wv_province.setViewAdapter(new ArrayWheelAdapter<String>(BaseApplicationLike.getInstance().mContext,
                mProvinceDatas));
        // 设置可见条目数量
        wv_province.setVisibleItems(5);
        if(provinceIndex != 0){
            wv_province.setCurrentItem(provinceIndex);
        }

        wv_city.setVisibleItems(5);
        wv_district.setVisibleItems(5);
        updateCities();
        updateAreas();
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = wv_city.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        wv_district.setViewAdapter(new ArrayWheelAdapter<String>(BaseApplicationLike.getInstance().mContext,
                areas));

        for(int i = 0; i < areas.length; i++){
            if(TextUtils.isEmpty(mCurrentDistrictName) && areas[i].contains(mCurrentDistrictName)){
                areaIndex = i;
                break;
            }
        }
        wv_district.setCurrentItem(areaIndex);
        mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
        mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = wv_province.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        wv_city.setViewAdapter(new ArrayWheelAdapter<String>(BaseApplicationLike.getInstance().mContext, cities));

        for(int i = 0; i < cities.length; i++){
            if(TextUtils.isEmpty(mCurrentCityName) && cities[i].contains(mCurrentCityName)){
                cityIndex = i;
                break;
            }
        }
        wv_city.setCurrentItem(cityIndex);
        updateAreas();
    }


    public void setOnDialogClickListener(OnDialogClickListener listener) {
        this.mListener = listener;
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == wv_province) {
            updateCities();
        } else if (wheel == wv_city) {
            updateAreas();
        } else if (wheel == wv_district) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_ok:
                mListener.onItemClick(mCurrentProviceName, mCurrentCityName, mCurrentDistrictName);
                dismiss();
                break;

            case R.id.btn_cancel:
                dismiss();
                break;
        }
    }

    public interface OnDialogClickListener {

        void onItemClick(String province, String city, String area);
    }
}
